package com.magicode.cms.service.impl;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.magicode.cms.common.assist.json.JsonOperation;
import com.magicode.cms.dao.IProgramDao;
import com.magicode.cms.entiy.base.BaseQuarterSet;
import com.magicode.cms.entiy.base.BroadPlatform;
import com.magicode.cms.entiy.base.Dictionary;
import com.magicode.cms.entiy.base.DictionaryType;
import com.magicode.cms.entiy.base.Enterprise;
import com.magicode.cms.entiy.base.Picture;
import com.magicode.cms.entiy.base.Program;
import com.magicode.cms.entiy.base.ProgramPersonRela;
import com.magicode.cms.service.IProgramService;

@Service("serviceprogram")
public class ProgramServiceImpl extends BaseServiceImpl<Program, IProgramDao> implements IProgramService{


	@Override
	public List<Map<String, Object>> getBeanInfo() {
		List<Map<String, Object>> beaninfo = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(json_key, "titleCn");
		map.put(json_title, "影视节目名称");
		map.put("width", 120);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "area");
		map.put(json_title, "地区");
		map.put("width", 50);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "programTypeNames");
		map.put(json_title, "类型");
		map.put("width", 70);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "enterpriseName");
		map.put(json_title, "制作公司");
		map.put("width", 60);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "dirNames");
		map.put(json_title, "导演");
		map.put("width", 120);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "otherPersonNames");
		map.put(json_title, "制片人");
		map.put("width", 120);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "status");
		map.put(json_title, "状态");
		map.put("width", 60);
		beaninfo.add(map);
		map = new HashMap<String, Object>();
		map.put(json_key, "subcribeTime");
		map.put(json_title, "发布时间");
		map.put("width", 120);
		beaninfo.add(map);
		return beaninfo;
	}

	@Override
	public List<JsonOperation> getOpts(String url,String id) {
		List<JsonOperation> opts = new ArrayList<JsonOperation> ();
		JsonOperation opt= new JsonOperation();
		opt.setName("修改");
		opt.setUrl(getCtx().getContextPath()+"/"+url+"/getinfo/"+id+"/edit"+url);
		opt.setType("edit");
		opts.add(opt);
		opt= new JsonOperation();
		opt.setName("删除");
		opt.setUrl(getCtx().getContextPath()+"/"+url+"/"+id+"?_requestMethod=delete");
		opt.setType("delete2");
		opts.add(opt);
		opt= new JsonOperation();
		opt.setName("预览");
		opt.setUrl(getCtx().getContextPath()+"/p/program/sec/" + id);
		opt.setType("preview");
		opts.add(opt);
		return opts;
	}
	
	@Override
	public String getHql(Map<String, String> querywhere) throws Exception {
		String fromHql =" from " +Program.class.getName()+" "+entity_alias_name+" ";
		fromHql += " left join "+entity_alias_name+".area as ar";
		//hql += " left join "+entity_alias_name+".programType ";
//		hql += " left join "+entity_alias_name+".enterprise ";
//		hql += " left join "+entity_alias_name+".director ";
//		hql += " left join "+entity_alias_name+".platform as pl ";
		fromHql += " left join "+entity_alias_name+".mainPic ";
		fromHql += " left join "+entity_alias_name+".author ";
		String whereHql = " where ";
		if(null!=querywhere && !querywhere.isEmpty()){
			whereHql += " 1 = 1 ";
			if(querywhere.containsKey(field_id)){
				whereHql = whereHql+" and "+entity_alias_name+".id = '"+querywhere.get(field_id)+"'";
			}
			if(querywhere.containsKey("titleCn")){
				whereHql = whereHql+" and "+entity_alias_name+".titleCn like '%"+querywhere.get("titleCn")+"%'";
			}
			if(querywhere.containsKey("title")){
				whereHql = whereHql+" and "+entity_alias_name+".titleCn = '"+querywhere.get("title")+"'";
			}
			if(querywhere.containsKey("titleEn")){
				whereHql = whereHql+" and "+entity_alias_name+".titleEn like '%"+querywhere.get("titleEn")+"%'";
			}
			if(querywhere.containsKey("areaId")){
				whereHql = whereHql+" and ar.id = '"+querywhere.get("areaId")+"'";
			}
			if(querywhere.containsKey("typeId")){
				fromHql += " , "+Dictionary.class.getName()+" type ";
				whereHql = whereHql+" and  (type in elements(t.programTypeList) and ( type.id = '"+querywhere.get("typeId")+"' or  type.parent.id = '"+querywhere.get("typeId")+"' ))  " ;
				//hql = hql+" and exists(select 1 from program_type_rela ptr where ptr.type_id in (select d.id from dictionary d where d.id='"+querywhere.get("typeId")+"' or d.parent_id='"+querywhere.get("typeId")+"') ) ";
			}
			if(querywhere.containsKey("statusId")){
				whereHql = whereHql+" and "+entity_alias_name+".status = '"+querywhere.get("statusId")+"'";
			}
		}
		
		return fromHql + whereHql;
	}

	@Override
	public List<Map<String, Object>> grid(Map<String, String> querywhere) {
		try {
			Integer start = this.getGridStartOrSize(querywhere, 0, field_grid_start);
			Integer size = this.getGridStartOrSize(querywhere, 20, field_grid_size);
			String hql = this.getHql(querywhere);
			hql += "order by "+entity_alias_name+".createTime desc ";
			Map<String,String> gridsel = new HashMap<String,String>();
			gridsel.put(field_id, ""+entity_alias_name+".id as id ");
			gridsel.put("titleCn", ""+entity_alias_name+".titleCn as titleCn ");
			gridsel.put("area", "ar.title as area ");
			//gridsel.put("programType", ""+entity_alias_name+".programType.title as programType ");
			gridsel.put("status", "case when "+entity_alias_name+".status = 0 then '草稿' "
					+ " when "+entity_alias_name+".status = 1 then '待审核' "
					+ " when "+entity_alias_name+".status = 2 then '已发布'  end as status ");
			gridsel.put("subcribeTime", ""+entity_alias_name+".subcribeTime as subcribeTime ");
			List<Map<String, Object>> resultList = this.queryMapDataList(hql, gridsel,start , size);
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			if(null!=resultList &&resultList.size()>0){
				//关联机构
				String hql1 = "select distinct new map(t.id as id , d.title as title ) from "+Enterprise.class.getName()+" d , "+Program.class.getName()+" t "
						+ " where  d in elements(t.enterpriseList) " ;
				String propertyName = "enterpriseName";
				resultList =  this.getRelateProByList(hql1, ",", propertyName, resultList);
				//节目类型
				hql1 = "select distinct new map(t.id as id , d.title as title ) from "+Dictionary.class.getName()+" d , "+Program.class.getName()+" t "
						+ " where  d in elements(t.programTypeList) " ;
				propertyName = "programTypeNames";
				resultList =  this.getRelateProByList(hql1, ",", propertyName, resultList);
				//关联导演
				hql1 = "select distinct new map(t.id as id , d.person.titleCn as title) from "+Program.class.getName()+" t,  " +ProgramPersonRela.class.getName()+" d "
						+ "where d in elements(t.directorList) ";
				propertyName = "dirNames";
				resultList =  this.getRelateProByList(hql1, ",", propertyName, resultList);
				//关联制片人
				hql1 = "select distinct new map(t.id as id , d.person.titleCn as title ) from "+Program.class.getName()+" t,  " +ProgramPersonRela.class.getName()+" d "
						+ "where d in elements(t.personList)";
				propertyName = "otherPersonNames";
				resultList =  this.getRelateProByList(hql1, ",", propertyName, resultList);
			}
			List<Map<String, Object>> programList = new ArrayList<Map<String,Object>>();
			if(null != resultList && resultList.size() > 0){
				for(Map map : resultList){
					if(null != map.get("subcribeTime")){
						String subcribeTime = df.format(map.get("subcribeTime"));
						map.put("subcribeTime", subcribeTime);
					}
					programList.add(map);
					
				}
			}
			return programList;
		} catch (Exception e) {
			e.printStackTrace();
			return new ArrayList<Map<String, Object>>();
		}
	}
	
	@Override
	public List<Dictionary> getProgramTypes(String id) {
		List<Dictionary> list = new ArrayList<Dictionary>();
		String hql = "select distinct d from "+ Dictionary.class.getName() + " d , " + Program.class.getName() + " t "
				+ " where d in elements(t.programTypeList) and t.id = :id order by d.id ";
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		try {
			list = this.programDao.getCommonDaoService().queryList(hql, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	@Override
	public List<Picture> getPictures(String id) {
		List<Picture> picList = new ArrayList();
		String sql = " select p from "+Picture.class.getName()+" p , "+Program.class.getName()+" t "
				+ " where p in elements(t.relaPics) and t.id = :id order by p.id ";
		Program program = null;
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		try {
			picList = this.programDao.getCommonDaoService().queryList(sql, map);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return picList;
	}
	
	@Override
	public List<ProgramPersonRela> getpersonList(String id) {
		List<ProgramPersonRela> personList = new ArrayList();
		String sql = " select ppr from "+ProgramPersonRela.class.getName()+" ppr left outer join fetch ppr.program p left outer join fetch ppr.person t "
				+ " where p.id = :id order by ppr.id ";
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		try{
			personList = this.programDao.getCommonDaoService().queryList(sql, map);
		} catch (Exception e1){
			e1.printStackTrace();
		}
		return personList;
	}
	
	@Override
	public List<Enterprise> getEnterpriseList(String id) {
		List<Enterprise> enterprise = new ArrayList();
		String sql = " select e from "+Enterprise.class.getName()+" e , " + Program.class.getName() + " p "
				+ " where e in elements(p.enterpriseList) and p.id=:id  order by e.id ";
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		try{
			enterprise = this.programDao.getCommonDaoService().queryList(sql, map);
		} catch (Exception e1){
			e1.printStackTrace();
		}
		return enterprise;
	}
	
	@Override
	public List<BaseQuarterSet> getbqsList(String id, Integer tp) {
		List<BaseQuarterSet> bqsList = new ArrayList();
		String sql = " select b from "+BaseQuarterSet.class.getName()
				+" b left join b.program p where p.id = :id and b.type = '"+tp+"' ";
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		try {
			bqsList = this.programDao.getCommonDaoService().queryList(sql, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return bqsList;
	}
	
	@Override
	public List<BroadPlatform> getbroPlfList(String id) {
		List<BroadPlatform> broadPlatformList = new ArrayList();
		String sql = " select p from "+BroadPlatform.class.getName()+" p , "+Program.class.getName()+" t "
				+ " where p in elements(t.platformList) and t.id = :id order by p.id desc ";
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		try {
			broadPlatformList = this.programDao.getCommonDaoService().queryList(sql, map);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return broadPlatformList;
	}
	
	@Override
	public List<Dictionary> getNetPlatformList(String id) {
		List<Dictionary> dicList = new ArrayList();
		String sql = " select p from "+Dictionary.class.getName()+" p , "+Program.class.getName()+" t "
				+ " where p in elements(t.netPlatformList) and t.id = :id order by p.orderCode asc ";
		Map<String, String> map = new HashMap<String, String>();
		map.put("id", id);
		try {
			dicList = this.programDao.getCommonDaoService().queryList(sql, map);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return dicList;
	}
	
	@Override
	public IProgramDao getDao() throws Exception {
		return programDao;
	}

	@Autowired
	@Qualifier("daoprogram")
	private IProgramDao programDao;

	public IProgramDao getProgramDao() {
		return programDao;
	}
	public void setProgramDao(IProgramDao programDao) {
		this.programDao = programDao;
	}
	
	
	@Override
	public List<Map<String,Object>> simpleSelect(Map<String,String> querywhere,Boolean isChannel){
		try {
			String hql = this.getHql(querywhere);
			Map<String,String> gridsel = new HashMap<String,String>();
			gridsel.put(field_id, ""+entity_alias_name+".id as id ");
			gridsel.put(field_titleCn, ""+entity_alias_name+".titleCn as text ");
//			if(isChannel){
//				gridsel.put("channelname", "pl.titleCn as channelName");
//			}
			return this.queryMapDataList(hql, gridsel,0 , 50);
		} catch (Exception e) {
			return new ArrayList<Map<String, Object>>();
		}
	}

	public List<Program> list(){
		String hql = " from " + Program.class.getName() + " t where 1=1 and t.initialWordDic is null";
		List<Program> list = programDao.getCommonDaoService().getListByHQL(hql);
		return list;
	}
	@Override
	public Program getbyTitleCn(Map map) throws Exception{
		Program program=(Program) programDao.getCommonDaoService().getByHQL("select t "+this.getHql(map), null);
		return program;
	}
	
	@Override
	public void deletePic(String picId,String programId) {
		this.programDao.deletePic(picId,programId);
	}

	@Override
	public List getDictionaryListByCode(String code) {
		List<Map<String, Object>> typeList = null;
		String sql = " select new map(d.id as id,d.title as title) from "+DictionaryType.class.getName()+" d  "
				+ " where d.code='"+code+"' and d.valid=1  order by d.id desc ";
		try {
			typeList = this.programDao.getCommonDaoService().getListByHQL(sql);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return typeList;
	}

}
